package cn.hdu.liang.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {

    private String serverPath = "/home/liang/WorkSpace/IDEA/Projects/FileUpload/upload";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建DiskFileItemFactory对象
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //2.创建ServletFileUpload对象
        ServletFileUpload sfu = new ServletFileUpload(factory);

        //3.设置文件编码
        sfu.setHeaderEncoding("utf-8");

        //4.解析文件
        try {
            List<FileItem> items = sfu.parseRequest(req);

            //5.获取文件信息
            for(FileItem item : items) {
                //6. 判断是文件，还是普通数据
                if(item.isFormField()) {
                    //普通数据
                    String fieldName = item.getFieldName();
                    if(fieldName.equals("info")) {
                        String info = item.getString("utf-8");
                        System.out.println(info);
                    }
                } else { //文件
                    //获取文件名称
                    String name = item.getName();
                    //获取文件实际内容
                    InputStream is = item.getInputStream();
                    //保存文件
                    File file = new File(serverPath + File.separator + name);
                    FileUtils.copyInputStreamToFile(is, file);
                }
            }
        } catch(FileUploadException e) {
            e.printStackTrace();
        }
    }
}
